package com.wuyoucar.util;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

public class HttpClientUtil {

    //处理get请求
    public static String getMethod(String url){
        String result = null;
        HttpClient client = HttpClients.createDefault();
        HttpGet get = new HttpGet(url);
        try {
            HttpResponse response = client.execute(get);
            System.out.println(response.getStatusLine());
            HttpEntity entity = response.getEntity();
            result = EntityUtils.toString(entity,"UTF-8");
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            get.releaseConnection();
        }
        return result;
    }

    //处理post请求
    public static String postMethod(String url,String json){
        String result = "";
        HttpClient client = HttpClients.createDefault();
        HttpPost post = new HttpPost(url);
        StringEntity se = null;
        try {
            se = new StringEntity(json,"UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        post.setHeader("Content-Type","application/json;charset=UTF-8");
        post.setEntity(se);
        try {
            HttpResponse response = client.execute(post);
            System.out.println(response.getStatusLine());
            HttpEntity entity = response.getEntity();
            result = EntityUtils.toString(entity);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            post.releaseConnection();
        }
        return result;
    }
}
